using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;
using WMS.WebApiRead.DTO;

namespace WMS.WebApiRead.Application.Commandhandler
{
    /// <summary>
    /// 产品信息查询命令处理器（分页查询+条件筛选+联表查询）
    /// </summary>
    public class ProductQueryCommandHandler : IRequestHandler<ProductQueryCommand, ApiResult<ApiPaging<List<ProductInfoResultDTO>>>>
    {
        private readonly IBaseRepository<ProductInfo> productRepository;
        private readonly IBaseRepository<WarehouseInfo> warehouseRepository;

        /// <summary>
        /// 构造函数，注入仓储接口
        /// </summary>
        public ProductQueryCommandHandler(
            IBaseRepository<ProductInfo> productRepository,
            IBaseRepository<WarehouseInfo> warehouseRepository)
        {
            this.productRepository = productRepository;
            this.warehouseRepository = warehouseRepository;
        }

        /// <summary>
        /// 处理产品信息查询命令（支持分页、筛选、联表查询）
        /// </summary>
        public async Task<ApiResult<ApiPaging<List<ProductInfoResultDTO>>>> Handle(ProductQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 联表查询：产品信息 LEFT JOIN 仓库表
                var query = from product in productRepository.GetAll()
                            where !product.IsDeleted // 只查询未删除的记录
                            join warehouse in warehouseRepository.GetAll()
                            on product.WarehouseId equals warehouse.WarehouseID into warehouseGroup
                            from warehouse in warehouseGroup.DefaultIfEmpty()
                            select new
                            {
                                Product = product,
                                WarehouseName = warehouse != null ? warehouse.WarehouseName : "未分配"
                            };

                // 条件筛选：货品编号（精确查询）
                if (!string.IsNullOrWhiteSpace(request.QueryDTO.ProductCode))
                {
                    query = query.Where(x => x.Product.ProductCode == request.QueryDTO.ProductCode);
                }

                // 条件筛选：产品名称（模糊查询）
                if (!string.IsNullOrWhiteSpace(request.QueryDTO.ProductName))
                {
                    query = query.Where(x => x.Product.ProductName.Contains(request.QueryDTO.ProductName));
                }

                // 条件筛选：单位（精确查询）
                if (!string.IsNullOrWhiteSpace(request.QueryDTO.Unit))
                {
                    query = query.Where(x => x.Product.Unit == request.QueryDTO.Unit);
                }

                // 条件筛选：仓库ID
                if (request.QueryDTO.WarehouseId.HasValue)
                {
                    query = query.Where(x => x.Product.WarehouseId == request.QueryDTO.WarehouseId.Value);
                }

                // 条件筛选：数据状态
                if (request.QueryDTO.DataStatus.HasValue)
                {
                    query = query.Where(x => x.Product.DataStatus == request.QueryDTO.DataStatus.Value);
                }

                // 计算总记录数
                var totalCount = query.Count();

                // 计算总页数
                var totalPage = (int)Math.Ceiling((double)totalCount / request.QueryDTO.PageSize);

                // 执行分页查询并投影到DTO
                var data = query
                    .OrderByDescending(x => x.Product.CreateTime) // 按创建时间倒序
                    .Skip((request.QueryDTO.PageIndex - 1) * request.QueryDTO.PageSize)
                    .Take(request.QueryDTO.PageSize)
                    .Select(x => new ProductInfoResultDTO
                    {
                        ProductId = x.Product.ProductId,
                        ProductCode = x.Product.ProductCode,
                        ProductName = x.Product.ProductName,
                        SpecificationModel = x.Product.SpecificationModel,
                        Unit = x.Product.Unit,
                        InboundUnitPrice = x.Product.InboundUnitPrice,
                        CurrentInventory = x.Product.CurrentInventory,
                        WarehouseId = x.Product.WarehouseId,
                        WarehouseName = x.WarehouseName, // 联表查询得到的仓库名称
                        IsDeleted = x.Product.IsDeleted,
                        DataStatus = x.Product.DataStatus,
                        CreateName = x.Product.CreateName,
                        CreateTime = x.Product.CreateTime,
                        UpdateName = x.Product.UpdateName,
                        UpdateTime = x.Product.UpdateTime
                    })
                    .ToList();

                // 返回分页结果
                return new ApiResult<ApiPaging<List<ProductInfoResultDTO>>>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询产品信息成功",
                    Data = new ApiPaging<List<ProductInfoResultDTO>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = data
                    }
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<ApiPaging<List<ProductInfoResultDTO>>>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询产品信息异常：{ex.Message}",
                    Data = new ApiPaging<List<ProductInfoResultDTO>>
                    {
                        TotalCount = 0,
                        TotalPage = 0,
                        Data = new List<ProductInfoResultDTO>()
                    }
                };
            }
        }
    }
}

